//
//  HMStatus.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/20.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

/// 服务器返回的一条微博数据模型
class HMStatus: NSObject {
    /// 微博创建时间
    var created_at: String?
    
    /// 微博ID
    var id: Int64 = 0
    
    /// 微博信息内容
    var text: String?
    
    /// 微博来源
    var source: String?
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数
    var attitudes_count: Int = 0
    
    // [String: String]
    var pic_urls: [[String: String]]?
    
    /// 用户模型
    var user: HMUser?
    
    /// 被转发的微博
    var retweeted_status: HMStatus?
    
    init(dcit: [String: Any]) {
        super.init()
        
        // 那字典中的key去模型中找对应的属性,找到对应的属性,将value赋值给对应的属性
        self.setValuesForKeys(dcit)
//        print("--------------")
        // setValuesForKeys 本质上会调用多次 setValue:forKey:
        // 字典中有多少个key就会调用多少次 setValue:forKey:
        // dcit = ["id": 1, "attitudes_count": 5, "comments_count": 1, "aaa": a, "bbb": bbb, "user": "{"a": "a"}"]
        // self.setValue(value: 1, forKey: "id")
        // self.setValue(value: 5, forKey: "attitudes_count")
        // self.setValue(value: 1, forKey: "comments_count")
        // self.setValue(value: "a", forKey: "aaa")
        // self.setValue(value: "bbb", forKey: "bbb")
        // self.setValue(value: "{"a": "a"}", forKey: "user")
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
//        print("key = \(key), value = \(value)")
        // 如果是 user key,我们自己来处理
        if key == "user" {
            if let dict = value as? [String : Any] {
                user = HMUser(dict: dict)
            }
            return
        }
        
        // 如果是被转发微博字典,自己转成被转发微博模型
        if key == "retweeted_status" {
            if let dict = value as? [String: Any] {
                retweeted_status = HMStatus(dcit: dict)
            }
            
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    // KVC不会帮我们 user 字典 转成模型,实际上还是字典,需要我们手动来转
    
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
    override var description: String {
        get {
//            let des = "created_at = \(created_at), id = \(id), text = \(text), source = \(source), reposts_count = \(reposts_count), comments_count = \(comments_count), attitudes_count = \(attitudes_count), pic_urls = \(pic_urls)"
            
            let keys = ["created_at", "id", "text", "source", "reposts_count", "comments_count", "attitudes_count", "pic_urls", "user", "retweeted_status"]
            let des = dictionaryWithValues(forKeys: keys)
            
            return "\n\n\t微博模型: \(des)"
        }
    }
}
